﻿using System;
using System.Collections.Generic;
using _5E.Utils.TypeHelper.Extension;

namespace _5E.Utils.DbHelper.EasySQL
{
    /// <summary>
    /// 程序说明：用于自生成单表SELECT、UPDATE、DELETE、INSERT SQL语句
    /// 创建作者：ahl5esoft
    /// 创建时间：2012-04-14
    /// </summary>
    internal class EasySQLCache
    {
        #region 变量

        private const string NOT_EXIST_ATTRIBUTE_ERROR_MESSAGE_FORMAT = "{0}不包含EasySQLAttribute";

        private Dictionary<Type, EasySQL> m_Cache = new Dictionary<Type, EasySQL>();

        #endregion

        #region 静态方法

        public EasySQL GetEasySQL(Type type)
        {
            EasySQL easySQLCreator;
            var notExist = !m_Cache.TryGetValue(type, out easySQLCreator);
            if (notExist)
            {
                easySQLCreator = CreateEasySQL(type);
            }
            return easySQLCreator;
        }

        private EasySQL CreateEasySQL(Type type)
        {
            var attribute = GetEasySQLAttribute(type);
            var easySQLCreator = new EasySQL(attribute.MappingPath);
            return easySQLCreator;
        }

        private EasySQLAttribute GetEasySQLAttribute(Type type)
        {
            EasySQLAttribute attribute;
            var hasAttribute = type.TryGetAttribute(out attribute);
            if (!hasAttribute)
            {
                var errorMessage = string.Format(NOT_EXIST_ATTRIBUTE_ERROR_MESSAGE_FORMAT, type.Name);
                throw new ArgumentNullException(errorMessage);
            }
            return attribute;
        }

        #endregion
    }
}
